package com.cxg.fairy.ec.main.cart;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.ViewStubCompat;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cxg.fairy.app.AccountManager;
import com.cxg.fairy.app.Latte;
import com.cxg.fairy.delegates.LatteDelegate;
import com.cxg.fairy.delegates.bottom.BottomItemDelegate;
import com.cxg.fairy.ec.detail.IGoodsDetailDelegate;
import com.cxg.fairy.ec.main.order.PostOrderDelegate;
import com.cxg.fairy.ec.pay.FastPay;
import com.cxg.fairy.ec.pay.IAlPayResultListener;
import com.cxg.fairy.net.RestClient;
import com.cxg.fairy.net.callback.IFailure;
import com.cxg.fairy.net.callback.ISuccess;
import com.cxg.fairy.ui.recycler.BaseDecoration;
import com.cxg.fairy.ui.recycler.MultipleFields;
import com.cxg.fairy.ui.recycler.MultipleItemEntity;
import com.cxg.fairy.util.GridDividerItemDecoration;
import com.cxg.fairy.util.MyDividerItemDecoration;
import com.cxg.fairy.util.log.LatteLogger;
import com.cxg.fairy.util.toasty.Toasty;
import com.diabin.latte.ec.R;
import com.diabin.latte.ec.R2;
import com.joanzapata.iconify.widget.IconTextView;

import java.util.ArrayList;
import java.util.WeakHashMap;

import butterknife.BindView;
import butterknife.OnClick;
import me.yokeyword.fragmentation.SupportFragmentDelegate;

/**
 * Created by CFairy
 */

public class ShopCartDelegate extends BottomItemDelegate implements ISuccess, ICartItemListener, IAlPayResultListener {

    private ShopCartAdapter mAdapter = null;
    //购物车数量标记
    private int mCurrentCount = 0;
    private int mTotalCount = 0;
    private double mTotalPrice = 0.00;
    private int delItemCount = 0;
    private int index = 0;
    //押金+运费
    String oPrice = Latte.getApplicationContext().getResources().getString(R.string.shop_cart_save_tag);

    //编辑状态
    private boolean editable = false;
    private String UUID = AccountManager.getSignUUID();

    @BindView(R2.id.rv_shop_cart)
    RecyclerView mRecyclerView = null;
    @BindView(R2.id.icon_shop_cart_select_all)
    IconTextView mIconSelectAll = null;
    @BindView(R2.id.stub_no_item)
    ViewStubCompat mStubNoItem = null;
    @BindView(R2.id.tv_shop_cart_total_price)
    AppCompatTextView mTvTotalPrice = null;
    @BindView(R2.id.tv_shop_cart_other_price)
    AppCompatTextView shopCartOtherPrice = null;
    @BindView(R2.id.itv_cart_edit)
    AppCompatTextView tvCardEdit = null;
    @BindView(R2.id.ll_cart_total_price)
    LinearLayoutCompat llCartTotalPrice = null;
    @BindView(R2.id.tv_shop_cart_pay)
    AppCompatTextView tvCreateorder = null;
    @BindView(R2.id.back_home)
    IconTextView iTvBackHome = null;

    @OnClick(R2.id.back_home)
    void onClickBackHome() {
        getSupportDelegate().pop();
    }

    //删除
    @OnClick(R2.id.itv_cart_edit)
    void onClickTvCartEdit() {
        int selectedItemCount = mAdapter.getSelectedItemCount();
        if (selectedItemCount > 0) {
            tvCardEdit.setVisibility(View.VISIBLE);
            RestClient.builder()
                    .url("shop_cart_del")
                    .loader(getContext())
                    .params("uuid", UUID)
                    .params("skuIds", mAdapter.getSelectedItemIds())
                    .success(new ISuccess() {
                        @Override
                        public void onSuccess(String response) {
                            //请求更新动态视图
                            updateRecycleView(response);
                            //物理删除数据项列表
                            removeSelectedItem();
                            //更新结算按钮
                            setPayButton();
                            //刷新SelectAllCheckBox 状态
                            if (mAdapter.getCartItemCount() == 0) {
                                cancelSelectAll();
                            }
                        }
                    })
                    .build()
                    .get();
        } else {
            Toasty.warning(getContext(), "请选择需要删除的商品！").show();
        }
    }

    //全选
    @OnClick(R2.id.icon_shop_cart_select_all)
    void onClickSelectAll() {
        Boolean isSelected;
        final int tag = (int) mIconSelectAll.getTag();
        mAdapter.setDoSelectedAll(true);
        if (tag == 0) {
            isSelected = true;
        } else {
            isSelected = false;
        }
        RestClient.builder()
                .url("shop_cart_all")
                .loader(getContext())
                .params("uuid", UUID)
                .params("isSelected", isSelected)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String responses) {
                        //请求更新动态视图
                        updateRecycleView(responses);
                        //物理更新动态视图
                        if (tag == 0) {
                            onSelectAll();
                        } else {
                            cancelSelectAll();
                        }

                        if (mAdapter.getCartItemCount() == 0) {
                            cancelSelectAll();
                            Toasty.warning(getContext(),"购物车是空的,您可以再逛逛.").show();
                        } else {
//                            checkItemCount();
                            mAdapter.notifyDataSetChanged();
                            mAdapter.setDoSelectedAll(false);
                        }
                        setPayButton();
                    }
                })
                .build()
                .post();
    }


    //删除选中（物理视图）
    void removeSelectedItem() {
        //要删除的数据
        for (int i = mAdapter.getCartItemCount(), j = 0; i > j; i--) {
            MultipleItemEntity entity = mAdapter.getData().get(i - 1);
            if (entity.getField(ShopCartItemFields.IS_SELECTED)) {
                mAdapter.getData().remove(entity);
                index--;
            }
        }
        mAdapter.notifyDataSetChanged();
        checkItemCount();
    }


    /**
     * 提交订单
     */
    @OnClick(R2.id.tv_shop_cart_pay)
    void onClickSubmit() {
        if (mAdapter == null)
            return;
        if (mAdapter.getSelectedItemCount() == 0)
            return;
        if (this.getParentDelegate() != null) {
            getParentDelegate().getSupportDelegate().start(new PostOrderDelegate());
        } else {
            getSupportDelegate().start(new PostOrderDelegate());
        }
    }


    /**
     * 检测item项为空时的视图
     */
    @SuppressWarnings("RestrictedApi")
    protected void checkItemCount() {
        final int count = mAdapter.getCartItemCount();
        if (count == 0) {
            try {
                final View stubView = mStubNoItem.inflate();
                final AppCompatTextView tvToBuy = (AppCompatTextView) stubView.findViewById(R.id.tv_stub_to_buy);
                tvToBuy.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getContext(), "你该购物啦！", Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (Exception e) {
                LatteLogger.e("error=","ViewStub must have a non-null ViewGroup viewParent");
            }

            mRecyclerView.setVisibility(View.GONE);
        } else {
            mRecyclerView.setVisibility(View.VISIBLE);
        }
    }

    protected void initIconSelectAll() {
        if (mAdapter.getSelectedItemCount() == mAdapter.getCartItemCount()) {
            onSelectAll();
        } else {
            cancelSelectAll();
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_shop_cart;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        initViewStatus();
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        initData();
    }

    @SuppressLint("NewApi")
    @Override
    public void onSuccess(String response) {
        final ArrayList<MultipleItemEntity> data = new ShopCartDataConverter().setJsonData(response).convert();
        mAdapter = new ShopCartAdapter(data);
        mAdapter.setDelegate(this);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                final int id = data.get(position).getField(MultipleFields.ID);
                LatteDelegate t = getParentDelegate();
                if (t != null) {
                    t.getSupportDelegate().start(IGoodsDetailDelegate.create(id));
                } else {
                    getSupportDelegate().replaceFragment(IGoodsDetailDelegate.create(id),false);
                }

            }
        });
        final GridLayoutManager manager = new GridLayoutManager(getContext(), 30);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setAdapter(mAdapter);

        GridDividerItemDecoration itemDecoration = new GridDividerItemDecoration(getContext());
        itemDecoration.setDrawable(getContext().getDrawable(R.drawable.my_decoration));

        mRecyclerView.addItemDecoration(itemDecoration);

        updateRecycleView(response);
        checkItemCount();
        initIconSelectAll();
        setPayButton();
        if (mAdapter.getCartItemCount() == 0) {
            cancelSelectAll();
        }
    }

    private void initData() {
        RestClient.builder()
                .url("getShoppingCartAndYouMightLike")
                .params("uuid",UUID)
                .loader(getContext())
                .success(this)
                .build()
                .post();
    }

    public void setPayButton() {
        int selectedItemCount = mAdapter.getSelectedItemCount();
        if (selectedItemCount > 0) {
            tvCreateorder.setEnabled(true);
            tvCreateorder.setText("去结算(" + selectedItemCount + ")");
            tvCreateorder.setBackgroundColor(Color.RED);
        } else {
            tvCreateorder.setEnabled(false);
            tvCreateorder.setText("去结算");
            tvCreateorder.setBackgroundColor(Color.GRAY);
        }
    }


    void onCancelSelectAll() {
        mIconSelectAll.setText("{icon-cart-circle-check-no}");
        mIconSelectAll.setTag(0);
        mAdapter.setDoSelectedAll(true);
        mAdapter.setIsSelectedAll(false);
        mAdapter.notifyItemRangeChanged(0, mAdapter.getCartItemCount());
    }

    /**
     * 请求响应更新视图
     *
     * @param response
     */
    public void updateRecycleView(String response) {
        mAdapter.getData().clear();
        ShopCartDataConverter sdc = new ShopCartDataConverter();
        ArrayList<MultipleItemEntity> datas = sdc.setJsonData(response).convert();
        Float amount = sdc.getAmount();
        Float freight = sdc.getFreight();
        mAdapter.getData().addAll(datas);
        //合计
        mTvTotalPrice.setText(String.format("%.2f", amount));
        //运费
        shopCartOtherPrice.setText(String.format(oPrice, freight + ""));
    }

    @Override
    public void onItemClick(double itemTotalPrice) {
        final double price = mAdapter.getTotalPrice();
        mTvTotalPrice.setText(String.format("%.2f", price));
    }

    @Override
    public void onPaySuccess() {

    }

    @Override
    public void onPaying() {

    }

    @Override
    public void onPayFail() {

    }

    @Override
    public void onPayCancel() {

    }

    @Override
    public void onPayConnectError() {

    }

    private void onSelectAll() {
        mIconSelectAll.setText("{icon-cart-circle-check-fullyes #FF0000}");
        mIconSelectAll.setTag(1);
        mAdapter.setIsSelectedAll(true);
    }

    private void cancelSelectAll() {
        mIconSelectAll.setText("{icon-cart-circle-check-no}");
        mIconSelectAll.setTag(0);
        mAdapter.setIsSelectedAll(false);
    }

    //激活标识
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initData();
            this.getSupportDelegate().hideSoftInput();
        }
    }

    @Override
    public boolean onBackPressedSupport() {
        toggleViewStatus();
        return true;
    }

    public void initViewStatus() {
        try {
            LatteDelegate t = this.getParentDelegate();
            if (t != null) {
                iTvBackHome.setVisibility(View.INVISIBLE);
            } else {
                iTvBackHome.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void toggleViewStatus() {
        try {
            LatteDelegate t = this.getParentDelegate();
            if (t != null) {
                super.onBackPressedSupport();
            } else {
                getSupportDelegate().pop();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
